package network;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class UdpEchoServer1 {
    private DatagramSocket socket = null;
    UdpEchoServer1(int port) throws SocketException {
        socket = new DatagramSocket(port);
    }

    public void start() throws IOException {
        System.out.println("程序启动");
        while(true) {
            //使用数据报来申请空间接收响应
            DatagramPacket requestPacket = new DatagramPacket(new byte[4096], 4096);
            socket.receive(requestPacket);
            //将二进制转化为字符串
            String request = new String(requestPacket.getData(), 0, requestPacket.getLength());
            //对接收的字符串进行处理
            String response = process(request);
            //使用数据报再进行返回
            DatagramPacket responsePacket = new DatagramPacket(response.getBytes(),  response.getBytes().length,
                    requestPacket.getSocketAddress());
            socket.send(responsePacket);

        }
    }
    private String process(String s) {
        return s;
    }

    public static void main(String[] args) throws IOException {
        UdpEchoServer1 server1 = new UdpEchoServer1(1314);
        server1.start();
    }
}
